package user

import (
	"context"
	"gin_grpc/common/log"
	pbMsg "gin_grpc/gateway/msg"
	"net/http"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
)

const (
	address     = "localhost:8082"
	defaultName = "world"
)

// Reg 用户注册
func Reg(this *gin.Context) {

	//建立链接
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Error("did not connect: %v", err)
	}
	defer conn.Close()
	c := pbMsg.NewGreeterClient(conn)

	// Contact the server and print out its response.
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]
	}
	// 1秒的上下文
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.SayHello(ctx, &pbMsg.HelloRequest{Name: name})
	if err != nil {
		log.Error("could not greet: %v", err)
	}
	log.Info("Greeting: %s", r.Message)

	this.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  r.Message,
	})
}
